package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.yuanfeng.business.dto.ShopClassBindDTO;
import com.yuanfeng.business.entity.ShopClassBindEntity;
import com.yuanfeng.business.feign.GoodsServiceClient;
import com.yuanfeng.business.mapper.ShopClassBindMapper;
import com.yuanfeng.business.service.ShopClassBindService;
import com.yuanfeng.business.vo.ShopClassBindVO;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.shop.ShopGoodsCatVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ShopClassBindServiceImpl
 * @Description  店铺经营类目-更新绑定类目时备份-孟响-19/04/16

 * @Author cyp
 * @Date 2023-07-04 16:30:05
 * @Version 1.0
 **/
@Service
public class ShopClassBindServiceImpl extends ServiceImpl<ShopClassBindMapper, ShopClassBindEntity>
        implements ShopClassBindService {

    @Autowired
    private GoodsServiceClient goodsServiceClient;
    @Override
    public ResponseResult verifyBusinessCategory(Map<String, Object> pram) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(pram.get("token").toString());
        String commonId = pram.get("commonId").toString();
        if(null == commonId || null == userInfo.getShopId() ){
            return ResponseResult.success(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg());
        }
        //判断当前店铺是否是自营店铺
        Boolean shopSelfSupport = this.baseMapper.queryShopSelfSupport(userInfo.getShopId());
        if(shopSelfSupport){
            return ResponseResult.success("自营店铺不校验经营类目");
        }
        //查询当前商品的类目id
        String catId = this.baseMapper.queryGoodsCatId(commonId);
        Integer exit = this.baseMapper.verifyBusinessCategory(catId,userInfo.getShopId());
        if(null != exit && exit > 0){
            return ResponseResult.success(BizCodeEnume.BUSINESS_CATEGORY_MEETS.getMsg());
        }else{
            return ResponseResult.success(BizCodeEnume.BUSINESS_CATEGORT_NOT_MATCH.getCode(),BizCodeEnume.BUSINESS_CATEGORT_NOT_MATCH.getMsg());
        }
    }

    @Override
    public ResponseResult deleteShopClassBindList(ShopClassBindDTO param) {
        int result = this.baseMapper.deleteById(param.getShopClassBindId());
        if (result > 0) {
            return ResponseResult.success();
        } else {
            return ResponseResult.fail(BizCodeEnume.DELETE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateSupplyShopCats(ShopClassBindDTO param) {
        //启用分类
        param.setShopClassBindEnable(CommonType.configEnable.AVAILABLE.getCode());
        param.setBabyCommission("0");
        //查询当前分类
        ResponseResult catResult = goodsServiceClient.queryCatByCatId(param.getProductClassId());
        ShopGoodsCatVO goodsCat = JSON.parseObject(JSON.toJSONString(catResult.getData()), ShopGoodsCatVO.class);
        if (null != goodsCat && goodsCat.getCatLevel() == 3) {
            param.setProductCatIds(goodsCat.getCatId().toString());
            param.setCommissionRate(goodsCat.getCatCommission());
            //添加或修改经营类目
            this.baseMapper.insertOrUpdateSelective(param);
        } else if (null != goodsCat && goodsCat.getCatLevel() == 2) {
            //查询当前分类的子分类
            Map<String, Object> map = ImmutableMap.<String, Object>builder().put("catParentId", param.getProductClassId()).build();
            insertOrUpdateSelective(param, map);
        } else {
            //查询当前分类的子分类
            Map<String, Object> map = ImmutableMap.<String, Object>builder().put("catParentId", param.getProductClassId()).build();
            ResponseResult catListResultOne = goodsServiceClient.queryCatList(map);
            List<ShopGoodsCatVO> childListOne = JSON.parseArray(JSON.toJSONString(catListResultOne.getData()), ShopGoodsCatVO.class);
            if (!childListOne.isEmpty()) {
                for (ShopGoodsCatVO childOne : childListOne) {
                    //查询当前分类的子分类
                    Map<String, Object> childMap = ImmutableMap.<String, Object>builder().put("catParentId", childOne.getCatId()).build();
                    insertOrUpdateSelective(param, childMap);
                }
            }
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryShopClassBindList(ShopClassBindDTO param) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ShopClassBindVO> page=this.baseMapper.selectShopClassBindList(new Query<ShopClassBindVO>().getPage(data),
                param);
        if(null != page && !page.getRecords().isEmpty()){
            for (ShopClassBindVO result : page.getRecords()) {
                List<String> catNames = goodsServiceClient.querySonCatByParentId(result.getProductClassId());
                result.setCatNames(catNames);
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deleteBindGoodsCat(Integer productClassId) {
        int flag = this.baseMapper.delete(new LambdaQueryWrapper<ShopClassBindEntity>()
                .eq(ShopClassBindEntity::getProductClassId, productClassId));
        if (flag > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    /**
     * 循环添加或修改经营类目
     *
     * @param param
     * @param childMap
     */
    private void insertOrUpdateSelective(ShopClassBindDTO param, Map<String, Object> childMap) {
        ResponseResult catListResultTwo = goodsServiceClient.queryCatList(childMap);
        List<ShopGoodsCatVO> childListTwo = JSON.parseArray(JSON.toJSONString(catListResultTwo.getData()), ShopGoodsCatVO.class);
        if (!childListTwo.isEmpty()) {
            for (ShopGoodsCatVO childTwo : childListTwo) {
                param.setProductCatIds(childTwo.getCatId().toString());
                param.setCommissionRate(childTwo.getCatCommission());
                //添加或修改经营类目
                this.baseMapper.insertOrUpdateSelective(param);
            }
        }
    }
}
